<script>
import axios from 'axios'
import { ElMessage } from 'element-plus'

function formatDate(dateStr) {
  if (!dateStr) return '';
  const d = new Date(dateStr);
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${y}/${m}/${day}`;
}

function statusTextAndTag(status) {
  if (status === 1) return { text: '进行中', tag: 'success' };
  if (status === 0) return { text: '已完成', tag: 'info' };
  if (status === -1) return { text: '待开始', tag: 'warning' };
  return { text: '未知', tag: 'default' };
}

export default {
  data() {
    return {
      plans: [],
      employees: [],
      employeesLoading: false,
      selectedPlan: null,
      selectedEmployee: null,
      employeeDialogVisible: false,
      detailDialogVisible: false,
      detailLoading: false,
      detailData: null,
      acceptDialogVisible: false,
      acceptForm: [],
      acceptLoading: false,
    }
  },
  methods: {
    async fetchPlans() {
      try {
        const res = await axios.get('http://127.0.0.1:8080/evaluator/getDisputesPlan', {
            headers:{
                'token':localStorage.getItem('token')
            }
        });
        if ((res.data.code === 0 || res.data.code === 200) && Array.isArray(res.data.data)) {
          this.plans = res.data.data.map(plan => {
            const statusObj = statusTextAndTag(plan.status);
            return {
              planId: plan.planId,
              planName: plan.planName,
              period: plan.assessmentCycle,
              target: plan.departmentName || '-', // 兜底
              dateRange: `${formatDate(plan.startDate)} - ${formatDate(plan.endDate)}`,
              statusText: statusObj.text,
              statusTagType: statusObj.tag,
            }
          });
          // 新增：刷新后重置所有弹窗和状态
          this.employeeDialogVisible = false;
          this.detailDialogVisible = false;
          this.acceptDialogVisible = false;
          this.selectedPlan = null;
          this.selectedEmployee = null;
          this.detailData = null;
          this.employees = [];
        } else {
          ElMessage.error(res.data && res.data.msg ? res.data.msg : '获取计划失败');
        }
      } catch (e) {
        ElMessage.error('网络错误，获取计划失败');
      }
    },
    async openEmployeeDialog(plan) {
      this.selectedPlan = plan;
      this.employeeDialogVisible = true;
      this.detailDialogVisible = false;
      this.selectedEmployee = null;
      this.employees = [];
      this.employeesLoading = true;
      try {
        const res = await axios.get('http://127.0.0.1:8080/evaluator/getDisputes', {
            headers:{'token':localStorage.getItem('token')},
            params: { planId: plan.planId } });
        
        if (res.data && (res.data.code === 0 || res.data.code === 200) && Array.isArray(res.data.data)) {
          this.employees = res.data.data;
        } else {
          this.employees = [];
          ElMessage.error(res.data && res.data.msg ? res.data.msg : '获取员工失败');
        }
      } catch (e) {
        this.employees = [];
        ElMessage.error('网络错误，获取员工失败');
      } finally {
        this.employeesLoading = false;
      }
    },
    async openDetailDialog(emp) {
      this.selectedEmployee = emp;
      this.detailDialogVisible = true;
      this.detailLoading = true;
      this.detailData = null;
      try {
        const res = await axios.get('http://127.0.0.1:8080/evaluator/getDisputesByEmpPlan',
         { headers:{'token':localStorage.getItem('token')},
            params: { planId: this.selectedPlan.planId, empId: emp.employeeId } });
        console.log(res);
        if (res.data && (res.data.code === 0 || res.data.code === 200) && res.data.data) {
          this.detailData = res.data.data;
        } else {
          this.detailData = null;
          ElMessage.error(res.data && res.data.msg ? res.data.msg : '获取详细信息失败');
        }
      } catch (e) {
        this.detailData = null;
        ElMessage.error('网络错误，获取详细信息失败');
      } finally {
        this.detailLoading = false;
      }
    },
    closeDetailDialog() {
      this.detailDialogVisible = false;
    },
    resetAll() {
      this.selectedPlan = null;
      this.selectedEmployee = null;
      this.employeeDialogVisible = false;
      this.detailDialogVisible = false;
    },
    openAcceptDialog(dispute) {
      // 只处理当前异议对应的指标（假设dispute里有indicatorId）
      if (dispute && dispute.indicatorId) {
        const indicator = (this.detailData.indicators || []).find(item => item.indicatorId === dispute.indicatorId);
        this.acceptForm = indicator ? [{
          indicatorId: indicator.indicatorId,
          comment: indicator.comment || '',
          score: indicator.score || 0
        }] : [];
      } else {
        // 如果没有indicatorId，默认全部
        this.acceptForm = (this.detailData.indicators || []).map(item => ({
          indicatorId: item.indicatorId,
          comment: item.comment || '',
          score: item.score || 0
        }));
      }
      this.acceptDialogVisible = true;
    },
    async submitAccept() {
      this.acceptLoading = true;
      try {
        const res = await axios.put('http://127.0.0.1:8080/evaluator/updataDisputesByEmpPlan', {
          employeeId: this.selectedEmployee.employeeId,
          planId: this.selectedPlan.planId,
          items: this.acceptForm
        }, {
          headers: { 'token': localStorage.getItem('token') }
        });
        if (res.data && (res.data.code === 0 || res.data.code === 200)) {
          ElMessage.success('受理成功');
          this.acceptDialogVisible = false;
          this.openDetailDialog(this.selectedEmployee); // 刷新详情
        } else {
          ElMessage.error(res.data && res.data.msg ? res.data.msg : '受理失败');
        }
      } catch (e) {
        ElMessage.error('网络错误，受理失败');
      } finally {
        this.acceptLoading = false;
      }
    },
  },
  mounted() {
    this.fetchPlans();
  }
}
</script>

<template>
  <div>
    <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px;">
      <h2 style="margin: 0;">考核计划列表</h2>
      <el-button type="primary" icon="el-icon-refresh" size="small" @click="fetchPlans" style="border-radius: 4px;">
        刷新
      </el-button>
    </div>
    <el-row :gutter="20">
      <el-col v-for="plan in plans" :key="plan.planId" :span="24" style="margin-bottom: 16px;">
        <el-card shadow="hover">
          <div style="display: flex; justify-content: space-between; align-items: flex-start;">
            <div>
              <div style="font-size: 18px; font-weight: bold; display: flex; align-items: center;">
                {{ plan.planName }}
                <el-tag :type="plan.statusTagType" size="small" style="margin-left: 8px;">
                  {{ plan.statusText }}
                </el-tag>
              </div>
              <div style="margin-top: 8px; color: #666;">
                <div style="margin-bottom: 4px;">
                  <el-icon style="vertical-align: middle;"><i class="el-icon-date"></i></el-icon>
                  <span style="margin-left: 4px;">考核周期：</span>{{ plan.period }}
                </div>
                <div style="margin-bottom: 4px;">
                  <el-icon style="vertical-align: middle;"><i class="el-icon-user"></i></el-icon>
                  <span style="margin-left: 4px;">考核对象：</span>{{ plan.target }}
                </div>
                <div>
                  <el-icon style="vertical-align: middle;"><i class="el-icon-timer"></i></el-icon>
                  <span style="margin-left: 4px;">考核时间：</span>{{ plan.dateRange }}
                </div>
              </div>
            </div>
            <el-button type="primary" size="small" icon="el-icon-user-solid" @click="openEmployeeDialog(plan)">
              查看人员
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 员工列表弹窗 -->
    <el-dialog title="有异议员工" v-model="employeeDialogVisible" width="40%" @close="selectedPlan = null">
      <el-table v-if="!employeesLoading && employees.length" :data="employees" border stripe size="small">
        <el-table-column prop="name" label="姓名" width="100" />
        <el-table-column prop="position" label="岗位" width="120" />
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button type="text" @click="openDetailDialog(scope.row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-empty v-else-if="!employeesLoading && !employees.length" description="暂无待处理的有异议员工" />
      <div v-else style="text-align:center;padding:32px 0;">
        <el-spinner />
      </div>
      <template #footer>
        <el-button @click="employeeDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog title="考核内容与异议信息" v-model="detailDialogVisible" width="50%" @close="closeDetailDialog">
      <div v-if="detailLoading" style="text-align:center;padding:32px 0;">
        <el-spinner />
      </div>
      <div v-else-if="detailData">
        <h4>考核结果</h4>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="总分">{{ detailData.result?.score ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="等级">{{ detailData.result?.evaluationLevel ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="detailData.result?.status === 1 ? 'success' : 'warning'">
              {{ detailData.result?.status === 1 ? '已确认' : '待确认' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
        <h4 style="margin-top: 16px;">考核指标</h4>
        <el-table :data="detailData.indicators || []" border stripe size="small">
          <el-table-column prop="indicatorName" label="指标名称" />
          <el-table-column prop="indicatorType" label="类型" />
          <el-table-column prop="weight" label="权重" />
          <el-table-column prop="score" label="分数" />
          <el-table-column prop="comment" label="评语" />
        </el-table>
        <h4 style="margin-top: 16px;">异议信息</h4>
        <el-table :data="detailData.disputes || []" border stripe size="small">
          <el-table-column prop="objectionContent" label="异议内容" />
          <el-table-column prop="status" label="状态">
            <template #default="scope">
              <el-tag :type="scope.row.status === 0 ? 'warning' : 'success'">
                {{ scope.row.status === 0 ? '待处理' : '已处理' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button
                v-if="scope.row.status === 0"
                type="primary"
                size="small"
                @click="openAcceptDialog(scope.row)"
              >受理</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-else style="text-align:center;color:#999;">暂无详细信息</div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <el-dialog
      title="受理异议"
      v-model="acceptDialogVisible"
      width="40%"
      :close-on-click-modal="false"
    >
      <el-form :model="acceptForm">
        <el-form-item
          v-for="(item, idx) in acceptForm"
          :key="item.indicatorId"
          :label="'指标' + (idx + 1)"
        >
          <div style="margin-bottom: 8px;">ID: {{ item.indicatorId }}</div>
          <el-input
            v-model="item.comment"
            placeholder="请输入评语"
            style="margin-bottom: 8px;"
          />
          <el-input-number
            v-model="item.score"
            :min="0"
            :max="100"
            label="分数"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="acceptDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="acceptLoading"
          @click="submitAccept"
        >提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

